import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { CustomerGoodCreateDto, CustomerGoodService, GoodCodeCreateDto, SelectOption, SelectResponse } from './customer-good.service';
import { ToasterService } from '@abp/ng.theme.shared';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { LookupService, SelectItem } from '../../shared/services/lookup.service';
import { Observable, of } from 'rxjs';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { GoodsSelectDialogComponent } from './goods-select-dialog.component';
import { GoodsModel } from './customer-good.service';

@Component({
  selector: 'app-customer-good-create',
  templateUrl: './customer-good-create.component.html',
  styleUrls: ['./customer-good-create.component.scss'],
  standalone: true,
  imports: [CommonModule, FormsModule]
})
export class CustomerGoodCreateComponent implements OnInit {
  @ViewChild('fileInput') fileInput: ElementRef;

  shippers$: Observable<SelectItem[]>;
  warehouses$: Observable<SelectOption[]>;
  reservedWarehouseAreas$: Observable<SelectOption[]>;
  orderTypes$: Observable<SelectOption[]>;

  // 主表单数据模型
  customerGood: Partial<CustomerGoodCreateDto> = {
    items: [],
    shipper: null,
    reservedWarehouseArea: null,
    warehouse: null,
    orderType: null,
    status: 'Initial' // 假设一个默认状态
  };

  // 初始化第一行明细
  goodCodeItems: GoodCodeCreateDto[] = [
    { productCode: '', quantity: null, plannedStorageSlots: null, status: 'Initial' }
  ];

  constructor(
    public modal: NgbActiveModal,
    private customerGoodService: CustomerGoodService,
    private toaster: ToasterService,
    private lookupService: LookupService,
    private modalService: NgbModal
  ) {}

  ngOnInit(): void {
    this.customerGood.items = this.goodCodeItems;
    this.loadLookups();
  }

  loadLookups(): void {
    const fakeShippers: SelectItem[] = [
      { id: 'coca-cola', name: '可口可乐饮料有限公司' },
      { id: 'mfg-001', name: '制造业001' },
      { id: 'soap-customer', name: '肥皂客户' },
      { id: 'tiankedao', name: '天可道' },
      { id: 'supplier-1', name: '供应商1' },
      { id: 'customer-1', name: '客户1' }
    ];
    this.shippers$ = of(fakeShippers);
    
    // 获取仓库数据
    this.customerGoodService.getWarehouses().subscribe({
      next: (response: SelectResponse) => {
        console.log('仓库数据:', JSON.stringify(response, null, 2));
        this.warehouses$ = of(response.items);
      },
      error: (error) => {
        console.error('获取仓库数据失败:', error);
      }
    });

    // 获取预约库区数据
    this.customerGoodService.getWarehouseAreas().subscribe({
      next: (response: SelectResponse) => {
        console.log('预约库区数据:', JSON.stringify(response, null, 2));
        this.reservedWarehouseAreas$ = of(response.items);
      },
      error: (error) => {
        console.error('获取预约库区数据失败:', error);
      }
    });

    // 获取订单类型数据
    this.customerGoodService.getOrderTypes().subscribe({
      next: (response: SelectResponse) => {
        console.log('订单类型数据:', JSON.stringify(response, null, 2));
        this.orderTypes$ = of(response.items);
      },
      error: (error) => {
        console.error('获取订单类型数据失败:', error);
      }
    });
  }

  // 添加一行商品明细
  addRow() {
    this.goodCodeItems.push({ productCode: '', quantity: null, plannedStorageSlots: null, status: 'Initial' });
  }

  // 删除指定行
  removeRow(index: number) {
    if (this.goodCodeItems.length > 1) {
      this.goodCodeItems.splice(index, 1);
    } else {
      this.toaster.info('至少需要保留一行明细！');
    }
  }

  // 待实现的合计功能
  batchAdd() {
    const totalQuantity = this.goodCodeItems.reduce((sum, item) => sum + (item.quantity || 0), 0);
    this.toaster.info(`当前总数量为：${totalQuantity}`);
  }
  // 保存
  save() {
    // 只校验货主
    if (!this.customerGood.shipper) {
      this.toaster.error('货主为必填项！');
      return;
    }

    // 更新主模型中的 items, 并将 null 转换回 0
    this.customerGood.items = this.goodCodeItems.map(item => ({
      ...item,
      quantity: item.quantity ?? 0,
      plannedStorageSlots: item.plannedStorageSlots ?? 0,
    }));
    
    // 设置主表状态
    const allYes = this.goodCodeItems.every(item => item.status === 'Yes');
    const anyNo = this.goodCodeItems.some(item => item.status === 'No');
    if (allYes) {
      this.customerGood.status = '已完成';
    } else if (anyNo) {
      this.customerGood.status = '计划中';
    } else {
      this.customerGood.status = '初始状态';
    }

    this.customerGoodService.create(this.customerGood as CustomerGoodCreateDto).subscribe({
      next: () => {
        this.toaster.success('成功创建进货通知单！');
        this.modal.close(true); // 关闭模态框并返回成功状态
      },
      error: (err) => {
        this.toaster.error('创建失败，请检查填写的内容！');
        console.error(err);
      }
    });
  }

  onFileSelected(event: Event): void {
    const element = event.currentTarget as HTMLInputElement;
    const fileList: FileList | null = element.files;

    if (fileList && fileList.length > 0) {
      const file = fileList[0];

      // Basic validation: file size limit (5MB)
      const maxSize = 5 * 1024 * 1024;
      if (file.size > maxSize) {
        this.toaster.error('文件大小不能超过 5MB！');
        this.clearAttachment();
        return;
      }

      // For now, just storing the file name.
      // A real implementation would involve uploading the file to a server.
      this.customerGood.attachmentPath = file.name;
      this.toaster.success('文件选择成功！');
    }
  }

  clearAttachment(): void {
    this.customerGood.attachmentPath = null;
    if (this.fileInput) {
      this.fileInput.nativeElement.value = '';
    }
  }

  openGoodsDialog(index: number) {
    const modalRef = this.modalService.open(GoodsSelectDialogComponent, { size: 'xl' });
    modalRef.result.then((selected: GoodsModel) => {
      console.log('选中的商品：', selected);
      if (selected) {
        this.goodCodeItems[index].productCode = selected.productCode;
        // 只回填商品编号，其他字段不回填
      }
    }).catch(() => {});
  }
} 